/*
 * FileName: GCStats.java
 * Author:   zzw
 * Date:     2018年11月15日
 * Description:
 */
package com.zzw.gc;

import sun.jvmstat.monitor.*;

import java.lang.management.ManagementFactory;
import java.net.URISyntaxException;

/**
 * 〈〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class GCStats {

    private static int getOwnPid() {
        String name = ManagementFactory.getRuntimeMXBean().getName();
        return Integer.parseInt(name.split("@")[0]);
    }

    // Oracle (Sun) HotSpot
    private static final String YOUNG_GC_MONITOR_NAME = "sun.gc.collector.0.invocations";
    private static final String FULL_GC_MONITOR_NAME  = "sun.gc.collector.1.invocations";

    // Oracle (BEA) JRockit
    // static final String YOUNG_GC_MONITOR_NAME = 'jrockit.gc.latest.yc.number';
    // static final String FULL_GC_MONITOR_NAME  = 'jrockit.gc.latest.oc.number';

    private static Monitor youngGCMonitor;
    private static Monitor fullGCMonitor;

    static {
        VmIdentifier vmIdentifier = null;
        try {
            vmIdentifier = new VmIdentifier("25056");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        int interval = 0;
        MonitoredHost monitoredHost = null;
        try {
            monitoredHost = MonitoredHost.getMonitoredHost(String.valueOf(vmIdentifier.getLocalVmId()));
        } catch (MonitorException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        MonitoredVm monitoredVm = null;
        try {
            monitoredVm = monitoredHost.getMonitoredVm(vmIdentifier, interval);
        } catch (MonitorException e) {
            e.printStackTrace();
        }
        try {
            youngGCMonitor = monitoredVm.findByName(YOUNG_GC_MONITOR_NAME);
        } catch (MonitorException e) {
            e.printStackTrace();
        }
        try {
            fullGCMonitor = monitoredVm.findByName(FULL_GC_MONITOR_NAME);
        } catch (MonitorException e) {
            e.printStackTrace();
        }
    }

    static int getYoungGCCount() {
        return (int) youngGCMonitor.getValue();
    }

    static int getFullGCCount() {
        return (int) fullGCMonitor.getValue();
    }

    private static class GCStatsThread extends Thread{
        @Override
        public void run() {
            int youngGCCount = GCStats.getYoungGCCount();
            int fullGCCount = GCStats.getFullGCCount();
            System.out.println(youngGCCount + "------" + fullGCCount);
        }
    }
    public static void main(String[] args) {
        new GCStatsThread().start();
        while (true){

        }
    }
}
